import skeletonCss from '../style/skeleton.less';
import popupCss from '../style/popup.less';
import payLoadingCss from '../style/payLoading.less';
import paymentButtonCss from '../style/paymentButton.less';
import toast from '../style/toast.less';
import { PaySDK } from './pay-sdk.js';
(function () {
  const pageBeforeunloadCallback = [];

  // 是否AB站
  function isPaymentAB() {
    return window['current_payment_type'] === 'AB';
  }

  /**
   * @description: 判断页面是否是ab A父页面通讯
   * @param {*} code 100 页面加载 200 页面加载完成 300数据验证 400显示支付 500隐藏支付
   * @param {*} data 传递数据
   * @return {*}
   */
  function postMessagePaymentA(code, data) {
    if (isPaymentAB()) {
      window.parent.postMessage({ type: 'paymentB', code: code, data: data }, '*');
    }
  }

  /**
   * @description: 判断页面是否是ab B父页面通讯
   * @param {*} code 100 验证失败 200 验证成功
   * @param {*} data 传递数据
   * @return {*}
   */
  function postMessagePaymentB(form, code, data) {
    $(form)[0].contentWindow.postMessage({ type: 'paymentA', code: code, data: data }, '*');
  }

  $.extend({
    // 动态创建script
    createElementStyle(id, content) {
      if (!window['createStyleIds']) {
        window['createStyleIds'] = [];
      }

      if (window['createStyleIds'].indexOf('id') === -1) {
        window['createStyleIds'].push(id);
        const style = document.createElement('style');
        style.innerHTML = content;
        document.head.appendChild(style);
      }
    },
    // 弹出框
    oemuiPopup(option) {
      const footer = option.footer || true;
      this.createElementStyle('oemuiPopup', popupCss);
      const popupFooter = `<div class="oemui-popup-footer">
            <a href="javascript:;" class="oemui-popup-clear oemui-popup-btn">${option.clearText}</a>
            <a href="javascript:;" class="oemui-popup-confirm oemui-popup-btn">${option.confirmText}</a>
          </div>`;

      const popupHeader = `<div class="oemui-popup-header">
          <span>${option.title}</span>
          <a href="javascript:;" style="display: flex;"><svg
            class="oemui-header-claer"
            t="1634191042040"
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="3072"
            width="20"
            height="20"
          >
            <path d="M571.008 511.936l313.088-311.04a42.688 42.688 0 0 0 0-58.816l-2.496-2.496a40.384 40.384 0 0 0-56.704 0l-313.088 313.6-313.088-311.04a40.384 40.384 0 0 0-56.704 0l-2.496 2.496a42.688 42.688 0 0 0 0 58.816l313.088 308.608-313.088 311.04a42.688 42.688 0 0 0 0 58.816l2.496 2.496a40.384 40.384 0 0 0 56.704 0l313.088-313.6 313.088 311.04a40.384 40.384 0 0 0 56.704 0l2.496-2.496a42.688 42.688 0 0 0 0-58.816z" fill="#1D1F21" p-id="3073">
            </path>
          </svg></a>
        </div>`;
      const popupHtml = $(`<div class="oemui-popup ${option.class}" style='--pay-color:${storeConfig.pay_color}'>
            <div class="oemui-popup-cover"></div>
            <div class="oemui-popup-body">
              <div class="oemui-popup-animation">
                ${option.header === null ? '' : option.header || popupHeader}
                <div class="oemui-popup-content">${option.content}</div>
                ${option.footer === null ? '' : option.footer || popupFooter}
              </div>
            </div>
          </div>
          `);

      function close() {
        popupHtml.remove();
      }

      popupHtml[0].addEventListener('touchmove', function (event) {
        event.preventDefault();
      });

      popupHtml.find('.oemui-popup-cover').click(function () {
        option.hide && option.hide();
        close();
      });
      popupHtml.find('.oemui-header-claer').click(function () {
        option.hide && option.hide();
        close();
      });
      popupHtml.find('.oemui-popup-clear').click(function () {
        option.cancel && option.cancel();
        close();
      });
      popupHtml.find('.oemui-popup-confirm').click(function () {
        option.ok && option.ok();
        close();
      });

      $('body').append(popupHtml);
      return {
        dom: popupHtml,
        close,
      };
    },

    toast({ container, text, time = 4000, isReplace = false }) {
      this.createElementStyle('toast', toast);
      if (container) {
        if (isReplace) {
          $(container).find('.oem-toast').text(text);
        } else {
          $(container).append(`<div class="oem-toast">${text}</div>`);
        }
        setTimeout(() => {
          $(container).find('.oem-toast').remove();
        }, time);
      } else {
        $('body').append(`<div class="oem-toast oem-toast-body">${text}</div>`);
        setTimeout(() => {
          $('body').find('.oem-toast').remove();
        }, time);
      }
    },

    // 显示骨架屏
    showSkeleton(container) {
      this.createElementStyle('showSkeleton', skeletonCss);
      var HTML = `<div class="oem-skeleton"><div class="oem-skeleton-row"></div><div class="oem-skeleton-row"></div></div>`;
      $(container).css({ height: '95px', position: 'relative', overflow: 'hidden' });
      $(container).html(HTML);
    },
    // 取消骨架屏
    hideSkeleton(container) {
      $(container).css({ height: '', position: 'relative' });
      $(container).find('.oem-skeleton').remove();
    },
    // 显示页面加载动画
    showPayLoading() {
      if ($('#oemui-toast').length > 0) {
        return;
      }
      this.createElementStyle('payLoading', payLoadingCss);
      var loadHtml = `
            <div class="oemui-toast" id="oemui-toast">
            <div class="oemui-toast-warp ">
              <div class="loading-box"></div>
              <div class="oemui-toast-text">${lang.customer.order_paying}</div>
            </div>
            </div>
            `;
      $('body').append(loadHtml);
    },
    // 隐藏页面加载动画
    hidePayLoading() {
      if ($('#oemui-toast').length > 0) {
        $('#oemui-toast').remove();
      }
    },
    formShowLoading({ size = 50, container, theme, position }) {
      $(container).css('pointer-events', 'none').css('position', 'relative');
      const style = document.createElement('style');
      style.innerHTML = `
            #common_tool-loading {
                position: ${position ? position : container ? 'absolute' : 'fixed'};
                top: 0; left: 0; bottom: 0; right: 0;
                background: ${theme ? (theme === 'dark' ? 'rgba(0, 0, 0, .8)' : '#ffffffe6') : ''};
                display: flex;
                align-items: center;
                justify-content: center;
                transition: opacity .2s linear;
                z-index:1000;
            }
            #common_tool-loading svg {
                animation: common_tool-loading-spin 1s linear infinite;
                fill: ${theme && theme === 'dark' ? '#fff' : '#666'}
            }
            @keyframes common_tool-loading-spin {
                from { transform: rotate(0deg); }
                to { transform: rotate(360deg); }
            }
            `;
      const loading = `
            <div id="common_tool-loading">
                <svg width="${size}" height="${size}" t="1644634233141" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="11473"><path d="M270.4 214.4C336 160 420 128 512 128c212 0 384 172 384 384h64c0-247.2-200.8-448-448-448-107.2 0-205.6 37.6-282.4 100l40.8 50.4z" p-id="11474"></path></svg>
            </div>
            `;
      document.head.appendChild(style);
      $(container || 'body').append(loading);
    },
    formHideLoading(container) {
      $(container).css('pointer-events', '');
      const $loading = $(container || 'body')
        .children('#common_tool-loading')
        .css('opacity', 0);
      setTimeout(() => $loading.remove(), 200);
    },
    // 页面禁用
    pageDisable() {
      if ($('#oemui-disable').length > 0) {
        return;
      }
      this.createElementStyle('pageDisable', `.oemui-disable {position: fixed;top: 0;left: 0;right: 0;bottom: 0;width:100%;height:100%;z-index: 999999;}`);
      $('body').append('<div class="oemui-disable" id="oemui-disable"></div>');
    },
    // 取消页面禁用
    pageEnable() {
      if ($('#oemui-disable').length > 0) {
        $('#oemui-disable').remove();
      }
    },
    // 动态创建js执行代码
    createScript(URL, callback) {
      // var newUrl = this.setUrlParams(URL,{v:new Date().getTime()})
      //当前url的script
      const currentScript = $("script[src='" + URL + "']");

      //是否存在；存在直接执行
      if (currentScript.length) {
        callback && callback();
        return;
      }

      //创建一个script标签
      const script = document.createElement('script');
      script.setAttribute('type', 'text/javascript');
      script.setAttribute('src', URL);
      script.onload = function () {
        callback && callback();
      };

      script.onerror = function () {};
      document.body.appendChild(script);
    },
    createPaymentButton(container, submitFun, verifiedFun) {
      var container = $(container);
      this.createElementStyle('paymentButton', paymentButtonCss);
      container.addClass('oem-paymentButton');
      container.attr('disabled', true);
      container.css({ backgroundColor: storeConfig.pay_color });
      container.append("<span class='payment-load'></span><span class='payment-text'>Pay</span>");
      container.paymentClick(submitFun, verifiedFun);
    },
    createPaymentCard(option) {
      var _that = this;
      postMessagePaymentA(100, '');
      if (!isPaymentAB()) {
        _that.formShowLoading({ theme: 'light', container: option.form });
      }
      // 如果存在src 加载js  返回加载成功初始化回调
      if (option.src) {
        this.createScript(option.src, function () {
          postMessagePaymentA(200, '');
          _that.formHideLoading(option.form);
          $(option.button).attr('disabled', false);
          // 成功回掉设置按钮可点击
          option.scriptSuccess &&
            option.scriptSuccess({
              enabledButton: function () {
                $(option.button).attr('disabled', false);
                setInterval(function () {
                  postMessagePaymentA(600, $(option.form).height());
                }, 1);
              },
              disableButton: function () {
                $(option.button).attr('disabled', true);
              },
            });
        });
      }

      if (option.button) {
        this.createPaymentButton(option.button, option.submit, option.verified);
      }
    },
    isLoadPaymentAB: false,
    paymentAMessageOption: { form: '' },
    paymentAPostMessage(option) {
      var _that = this;
      _that.paymentAMessageOption = option;
      _that.formShowLoading({ theme: 'light', container: _that.paymentAMessageOption.form });
      async function postMessageCallback(event) {
        if (event.data && event.data.type && event.data.type == 'paymentB') {
          if (event.data.code == 100) {
            // _that.formHideLoading(this.paymentAMessageOption.form);
          }
          if (event.data.code == 200) {
            _that.formHideLoading(_that.paymentAMessageOption.form);
          }
          if (event.data.code == 300) {
            const oemBeforePaymentResults = window['oemBeforePayment'] ? await window['oemBeforePayment']() : true;
            if (oemBeforePaymentResults) {
              postMessagePaymentB(_that.paymentAMessageOption.iframe, 200, '');
            } else {
              postMessagePaymentB(_that.paymentAMessageOption.iframe, 100, '');
            }
          }
          if (event.data.code == 400) {
            $.showPayLoading();
          }
          if (event.data.code == 500) {
            $.hidePayLoading();
          }
          if (event.data.code == 600) {
            if (event.data.data) {
              $(_that.paymentAMessageOption.iframe).height(event.data.data);
            }
          }
        }
      }

      if (!this.isLoadPaymentAB) {
        this.isLoadPaymentAB = true;
         window.addEventListener("message", postMessageCallback);
      }
    },

    createThreePayment: function (options) {
      return new PaySDK(options);
    },
    sendPaymentBtoPaymentA(code, data) {
      window.parent.postMessage({ type: 'paymentB', code: code, data: data }, '*');
    },
    paymentBPostMessage(option) {
      window.addEventListener('message', function (event, s) {
        if (event.data && event.data.type && event.data.type == 'paymentA') {
          // 100 父窗口验证处理失败 200 验证成功提交数据
          if (event.data.code == 200) {
            option.success();
          }
          if (event.data.code == 100) {
            option.fail();
          }
        }
      });
    },
  });

  function throttle(func, wait) {
    var previous = 0;
    return function () {
      let now = Date.now();
      let context = this;
      let args = arguments;
      if (now - previous > wait) {
        func.apply(context, args);
        previous = now;
      }
    };
  }

  // 支付节流
  $.fn.throttleClick = function (fun) {
    $(this).click(throttle(fun, 500));
  };

  // 支付节流 验证数据是否完善
  $.fn.paymentClick = function (fun, verifiedFun) {
    var _that = $(this);

    function showLoading() {
      _that.addClass('active');
    }

    function hideLoading() {
      _that.removeClass('active');
    }

    // 提交数据
    function submit() {
      fun({
        hideLoading() {
          hideLoading();

          // 不是AB站隐藏支付加载
          isPaymentAB() ? postMessagePaymentA(500, '') : $.hidePayLoading();
        },
        showLoading() {
          // 不是AB站显示支付加载
          isPaymentAB() ? postMessagePaymentA(400, '') : $.showPayLoading();
        },
      });
    }

    //异步数据处理
    async function asyncCallBack() {
      if (_that.attr('disabled')) {
        return false;
      }
      showLoading();

      // 处理自定义验证
      if (verifiedFun) {
        const retVerified = verifiedFun();
        if (retVerified instanceof Promise) {
          const retPromise = await retVerified;
          if (!retPromise) {
            hideLoading();
            return false;
          }
        } else {
          if (!retVerified) {
            hideLoading();
            return false;
          }
        }
      }
      // if (verifiedFun && !verifiedFun()) {
      //     hideLoading();
      //     return false;
      // }

      if (!isPaymentAB()) {
        //提交之间执行扩展的方法
        const oemBeforePaymentResults = window['oemBeforePayment'] ? await window['oemBeforePayment']() : true;
        if (oemBeforePaymentResults) {
          submit();
        } else {
          hideLoading();
        }
      } else {
        postMessagePaymentA(300, '');
      }
    }

    pageBeforeunloadCallback.push(hideLoading);

    _that.click(
      throttle(function () {
        asyncCallBack();
      }, 500)
    );

    // 如果是AB站创建页面监听
    if (isPaymentAB()) {
      window.addEventListener('message', function (event, s) {
        if (event.data && event.data.type && event.data.type == 'paymentA') {
          // 100 父窗口验证处理失败 200 验证成功提交数据
          if (event.data.code == 200) {
            submit();
          }
          if (event.data.code == 100) {
            hideLoading();
          }
        }
      });
    }
  };
})();
